package core.upintf;

import io.stripframe.FrameProcessor;
import io.stripframe.FrameStripper;
import io.stripframe.RawlStripper;

import java.nio.channels.SocketChannel;

import org.apache.log4j.Logger;

import protocol.pv.PVCommand;
import protocol.pv.PVCommandException;

import com.seari.ssmq.client.ConnectionException;
import com.seari.ssmq.client.Connector;
import com.seari.ssmq.client.IConnector;
import com.seari.ssmq.client.IEventDisposal;
import com.seari.ssmq.client.IServerList;
import com.seari.ssmq.client.ServerList;
import com.seari.ssmq.client.protocol.ITextMessage;
import com.seari.ssmq.client.protocol.TextMessage;

import core.ProcessThread;


public class DM2Client implements UpInterface{

	private static final Logger logger = Logger.getLogger(DM2Client.class);
	private IConnector client;
	
	private final DM2ClientInfo info;
	
	public DM2Client(DM2ClientInfo info){
		this.info = info;
		this.initClient(info);
	}
	
	private void initClient(DM2ClientInfo info) {
		try {
			IServerList list = new ServerList(info.getAddress_list()[0].getIp(),
					info.getAddress_list()[0].getPort(),
					info.getAddress_list()[0].getRetrytime());
			int servercount = info.getServerCount();
			//has more connection
			
			if (servercount > 1){
				for (int i = 1;i<servercount-1;i++){
					list.addConnect(info.getAddress_list()[i].getIp(), 
							info.getAddress_list()[i].getPort(), 
							info.getAddress_list()[i].getRetrytime());
				}
			}
			client = Connector.newInstance(list);
			client.attachEventDisposal(new DMClientEventListener(this));
			//client.attachEventDisposal(new Listener());
			client.getSender().setAutoResend(false);
			client.register(info.getType(),info.getUserid(),
					info.getPwd());
			
		} catch (Exception e) {
			logger.fatal("DM2 host init exception",e);
			System.exit(1);		
		}	
	}
	
	public void close() {
		client.disconnect();
	}

	public void closeTemporarily() {
		//not supported herre
	}

	public boolean isConnected() {
		return client.isConnected();
	}

	public void run() throws ConnectionException {
		client.connect();
	}

	public boolean write(PVCommand pvCommand) {
		if (!info.isSendtoComm())
			return true;
		String frame = pvCommand.output();
		logger.debug("write to server:"+frame);
		ITextMessage text =new TextMessage(frame);
		return this.client.getSender().send(text);
	}

}

class Listener implements IEventDisposal{
	private static final Logger logger = Logger.getLogger(Listener.class);
	private FrameStripper stripper;
	private ReceiveMSGWorker worker;
	//private class DMClientFrameProcessor implements FrameProcessor {
	//	public void process(String s) {
	//		System.out.println(s);
//			try {
//				PVCommand command = PVCommand.genPVCommand(s);
//				if (command.getCommandID().equals(PVCommand.SOCKET_BEAT)) {
//					
//					//command.decode(null);
//				}
//				else {
//					String msgid= command.getCommandID();
//					if (msgid!=null){
//						ProcessThread thd=powerAlgo.processThreads.get(msgid);
//						if (thd !=null){
//							thd.feedCommand(command);
//						}
//					}
//					
//				}
//			} catch (PVCommandException e) {
//				logger.error("pv command error", e);						
//			} catch (Throwable e) {
//				logger.error("runtime error", e);
//			}
//		}
//	}
	
	//private DMClientFrameProcessor processor=new DMClientFrameProcessor();

	/**
	 * ������Ϣ
	 */
	public void onConnect(SocketChannel arg0) {
		// TODO Auto-generated method stub
		//stripper= new RawlStripper();
		//stripper.attachObserver(new DMClientFrameProcessor());
		worker= new ReceiveMSGWorker();
		worker.start();
	}

	/**
	 * �ж���Ϣ
	 */
	public void onDisconnect(SocketChannel arg0) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * ��ݽ�����Ϣ
	 */
	public void onReceived(SocketChannel arg0, String arg1) {
		// TODO Auto-generated method stub
		//System.out.println(arg1);
		//stripper.putString(arg1);
		this.worker.feedTask(new ReceiveMSGTask(arg1));
	}
    
	/**
	 * ע����Ϣ
	 */
	public void onRegistered(int clientid, boolean isRegistered) {
	
	}
	
}
